package top.retain;

/**
 * @author ivorfan
 * @date 2021/7/11 10:01
 */
public class FinalizeTest {
    private static FinalizeTest obj;
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("调用finalize()");
        // 第一次自救
        obj = this;
    }

    public static void main(String[] args) {
        try {
            obj = new FinalizeTest();
            obj = null;
            System.gc();
            System.out.println("第一次gc");
            Thread.sleep(2000);
            if (obj == null) {
                System.out.println("obj is dead");
            } else {
                System.out.println("obj is still alive");
            }
            obj = null;
            System.out.println("第二次gc");
            Thread.sleep(2000);
            if (obj == null) {
                System.out.println("obj is dead");
            } else {
                System.out.println("obj is still alive");
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
